package com.ymt.bpm.sso.servlet;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by Johnny on 2016/12/28.
 */
@WebServlet(urlPatterns="/servlet/sso/logout", description="Servlet For logout")
public class LogoutServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);

        if (logger.isLoggable(Level.FINER)) {
            logger.finer("doGet");
        }

        String path = req.getParameter("path");
        if (path==null) {
            path = req.getContextPath();
            if (path!=null && path.length()==0) {
                path = "/";
            }
        }

        if (logger.isLoggable(Level.FINER)) {
            logger.finer("path="+path);
        }

        //remove session
        Enumeration<String> attrs = req.getSession().getAttributeNames();
        while (attrs.hasMoreElements()) {
            req.getSession().removeAttribute(attrs.nextElement());
        }
        req.getSession().invalidate();

        //remove all cookies
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie:cookies) {
            cookie.setPath("/");
            cookie.setMaxAge(0);
            cookie.setValue(null);
            if (logger.isLoggable(Level.FINER)) {
                logger.finer("cookie path ======" + cookie.getPath());
                logger.finer("cookie domain ====" + cookie.getDomain());
                logger.finer("cookie name ======" + cookie.getName());
                logger.finer("cookie value ====="+cookie.getValue());
            }
        }

        //call logout
        req.logout();

        //redirect logout url
        resp.sendRedirect(path);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        logger.finer("doPost");
        doGet(req, resp);
    }

    @Override
    public void init() throws ServletException {
        //super.init();
        logger.finer("init");
    }
}
